import {SOCKET_BASE_URL} from "@/utils/constant.js"
let urlProtocol = 'wss://'
let wsInstance = null;
let sendCallback = null
let socketTask = null;
let connectTimer=null;

const connectWebsocket = (socketParams) => {
	let socketUrl=`${SOCKET_BASE_URL}/websocket_4_openai?${socketParams}`
	console.log(socketUrl,">>>socketUrl")
	return new Promise((resolve, reject) => {
		
		if (!socketTask) {
			socketTask = uni.connectSocket({
				url: `${socketUrl}`, //仅为示例，并非真实接口地址。
				complete: () => {
					return socketTask;
				}
			});
			connectTimer=setTimeout(()=>{
				reject({
					code:500,
					msg:'连接失败'
				})
				socketTask=null;
			},3000)
			socketTask.onOpen((res) => {
				clearTimeout(connectTimer);
				console.log("连接成功")
				console.log(res, ">>>>>>>>>resOPen")
				console.log(">>>>socketTask.readyState", socketTask.readyState)
				// f([2,3].includes(socketTask.readyState)){//closing 或 closed
				//         socket.close();
				//         socket = null;
				//         openWs();        
				//     }


				socketTask.onMessage(res => {
					// ...to do
					console.log("接收到数据", res, ">>>>>>>>>>>>>>")
					sendCallback && sendCallback(res)
				});
				socketTask.onClose(() => {
					socketTask = null;
					console.log('close')
					sendCallback && sendCallback({data:""})
				});
				let timer = null;
				timer = setTimeout(() => {
					resolve({
						code: 0,
						msg: '已连接'
					})
				}, 800)
				socketTask.onError((err) => {
					console.log("WebSocket连接失败", err);
					clearTimeout(timer)
					sendCallback && sendCallback({data:""})
					reject(err)
				})
				
			})

		} else {
			resolve({
				code: 0,
				msg: '已连接'
			})
		}
	})

}

export const sendWsData = (message, callback, socketParmas) => {
	console.log("开始发送数据", message)
	return new Promise((resolve, reject) => {
		sendCallback = callback;
		if (socketTask) {
			socketTask.send({
				data: message
			})
			resolve(true)
		} else {
			reject(false)
		}
	})
}

export const connect = (socketParams) => {
	return connectWebsocket(socketParams)
	return new Promise(async (resolve, reject) => {
		// let connectResult = await connctWebsocket(socketParams).catch((err) => {
		//   reject(err)
		// })
		// console.log('connectResult>>>>',connectResult)
		// if (connectResult) {
		//   resolve()
		// }
		// return;
		// else{
		//   reject();
		// }
	})
}

export const closeSocket = () => {
	// uni.closeSocket()
	if (socketTask) {
		socketTask.close();
	}

	setTimeout(() => {
		socketTask = null;
	}, 300)
}
